<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        style="width: 200px;"
        class="filter-item"
        placeholder="请输入企业名称"
        v-model.trim="queryForm.bussinessName"
        maxlength="20"
      >
      </el-input>
      <el-input
        style="width: 200px;"
        class="filter-item"
        placeholder="请输入项目名称"
        v-model.trim="queryForm.name"
        maxlength="20"
      >
      </el-input>
      <el-input
        style="width: 200px;"
        class="filter-item"
        placeholder="请输入项目负责人"
        v-model.trim="queryForm.projectUser"
        maxlength="20"
      >
      </el-input>
      <el-input
        style="width: 200px;"
        class="filter-item"
        placeholder="请输入项目地址"
        v-model.trim="queryForm.addr"
        maxlength="20"
      >
      </el-input>
      <el-button
        class="filter-item"
        @click="doSearchQuery"
        type="primary"
        icon="el-icon-search"
        >查询</el-button
      >
      <el-button
        v-permission="'project:add'"
        class="filter-item"
        style="margin-left: 10px;"
        @click="openCreateDialog"
        type="success"
        icon="el-icon-plus"
        >新增</el-button
      >
    </div>
    <el-table v-loading="loading" :data="records" style="width: 100%">
      <el-table-column prop="rowId" label="项目ID" width="100" align="center">
      </el-table-column>
      <el-table-column prop="name" label="项目名称" width="450" align="center">
      </el-table-column>
      <el-table-column
        prop="bussinessName"
        label="企业名称"
        width="250"
        align="center"
      >
      </el-table-column>
      <el-table-column
        prop="projectUser"
        label="项目负责人"
        width="150"
        align="center"
      >
      </el-table-column>

      <el-table-column
        prop="phone"
        label="项目负责人电话"
        width="150"
        align="center"
      >
      </el-table-column>
      <el-table-column prop="addr" label="项目地址" width="150" align="center">
      </el-table-column>
      <el-table-column
        prop="createTime"
        label="创建时间"
        width="250"
        align="center"
      >
      </el-table-column>
      <el-table-column
        align="center"
        label="操作"
        class-name="small-padding "
        width="170"
        fixed="right"
      >
        <template slot-scope="scope">
          <el-button
            type="success"
            icon="el-icon-plus"
            size="mini"
            @click="openProjectDevice(scope.row)"
            circle
            title="查看详情"
            v-permission="'project:detail'"
          ></el-button>
          <el-button
            type="primary"
            size="mini"
            @click="editProject(scope.row)"
            icon="el-icon-edit"
            circle
            title="编辑项目"
            v-permission="'project:update'"
          ></el-button>
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.row.rowId)"
            icon="el-icon-delete"
            circle
            title="删除项目"
            v-permission="'project:delete'"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryForm.current"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="queryForm.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="queryForm.total"
      >
      </el-pagination>
    </div>

    <el-dialog
      :title="`新增项目`"
      :visible.sync="addBulidVisible"
      width="50%"
      :close-on-click-modal="false"
    >
      <el-form
        :model="addProjectForm"
        label-width="100px"
        :rules="addProjectFormRules"
        ref="addProjectForm"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="项目名称:" prop="name">
              <el-input
                v-model="addProjectForm.name"
                auto-complete="off"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目地址:" prop="addr">
              <el-input
                v-model="addProjectForm.addr"
                auto-complete="off"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="项目负责人:" prop="projectUser">
              <el-input
                v-model="addProjectForm.projectUser"
                auto-complete="off"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="负责人电话:" prop="phone" maxlength="11">
              <el-input
                v-model="addProjectForm.phone"
                auto-complete="off"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addBulidVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveProjectForm">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="编辑项目"
      :visible.sync="dialogFormVisible"
      width="20%"
      :close-on-click-modal="false"
    >
      <el-form
        :model="exampleForm"
        label-width="110px"
        :rules="exampleFormRules"
        ref="exampleForm"
      >
        <el-form-item label="项目名称:" prop="name">
          <el-input
            v-model.trim="exampleForm.name"
            placeholder="项目名称"
            auto-complete="off"
            maxlength="20"
          ></el-input>
        </el-form-item>
        <el-form-item label="项目负责人:" prop="projectUser">
          <el-input
            v-model.trim="exampleForm.projectUser"
            placeholder="项目负责人"
            auto-complete="off"
            maxlength="20"
          ></el-input>
        </el-form-item>
        <el-form-item label="项目负责人电话:" prop="phone">
          <el-input
            v-model.trim="exampleForm.phone"
            placeholder="项目负责人电话"
            auto-complete="off"
            maxlength="20"
          ></el-input>
        </el-form-item>
        <el-form-item label="项目地址:" prop="addr">
          <el-input
            v-model.trim="exampleForm.addr"
            placeholder="项目地址"
            auto-complete="off"
            maxlength="20"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateProject">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="项目设备"
      :visible.sync="projectDeviceVisible"
      :append-to-body="true"
      width="50%"
      height="300"
    >
      <el-table
        :data="deviceTable"
        stripe
        max-height="400"
        style="height:400px;width:1255px"
      >
        <el-table-column prop="rowId" label="ID" width="50" align="center">
        </el-table-column>
        <el-table-column
          prop="deviceCode"
          label="设备编号"
          width="150"
          align="center"
        >
        </el-table-column>
        <el-table-column
          prop="deviceType"
          label="设备类型"
          width="100"
          align="center"
        >
          <template slot-scope="scope">
            <span
              class="device-type"
              :class="{
                控制设备: scope.row.deviceType === '1',
                传输设备: scope.row.deviceType === '2'
              }"
            ></span>
            {{ Dicts.DEVICE_TYPE[scope.row.deviceType] }}
          </template>
        </el-table-column>
        <el-table-column
          prop="connectStatus"
          label="状态"
          width="100"
          align="center"
        >
          <template slot-scope="scope">
            <span
              class="device-status"
              :class="{
                online: scope.row.maintenanceStatus === '1',
                offline: scope.row.connectStatus === '2',
                sleep: scope.row.connectStatus === '5'
              }"
            ></span>
            {{ Dicts.DEVICE_CONNECT_STATUS[scope.row.maintenanceStatus] }}
          </template>
        </el-table-column>
        <el-table-column
          prop="bussinessName"
          label="所属企业"
          width="150"
          align="center"
        >
        </el-table-column>
        <el-table-column
          prop="boardAddr"
          label="设备板地址"
          width="150"
          align="center"
        >
        </el-table-column>
        <el-table-column
          prop="ipAddr"
          label="设备IP地址"
          width="150"
          align="center"
        >
        </el-table-column>
        <el-table-column
          prop="usedMem"
          label="内存使用率"
          width="100"
          align="center"
        >
        </el-table-column>
        <el-table-column
          prop="usedCpu"
          label="cpu使用率"
          width="100"
          align="center"
        >
        </el-table-column>
        <el-table-column
          prop="termiPhoneNum"
          label="通信号码"
          width="150"
          align="center"
        >
        </el-table-column>

        <el-table-column
          prop="createTime"
          label="操作日期"
          width="150"
          align="center"
        >
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="closeDialog">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  queryProject,
  // deleteBulidIng,
  deleteProject,
  // getBussinessDetail,
  queryProjectDetail,
  saveUnit,
  saveProject,
  updateProject,
  uploadBuildingFile,
  selectAllCommunity,
  selectByCommunityIdBuilding
} from '@/api/community'
import { queryProvince, getCity, getDistrict } from '@/api/area'
import { findDeviceByProject } from '@/api/device'
export default {
  name: 'building',
  data() {
    var checkStartNum = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入起始数量'))
      } else {
        if (this.addUnitForm.count !== '') {
          this.$refs.addUnitForm.validateField('count')
        }
        callback()
      }
    }
    var checkNum = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入结束数量'))
      } else {
        if (value < this.addUnitForm.startCount) {
          callback(new Error('起始数要小于结束数'))
        } else {
          callback()
        }
      }
    }
    return {
      radioNum: '1',
      fileVisible: false,
      addUnitVisible: false,
      projectDeviceVisible: false,
      loading: false,
      dialogFormVisible: false,
      addBulidVisible: false,
      single: true,
      double: false,
      exampleForm: [
        {
          rowId: undefined,
          bussinessId: undefined,
          name: '',
          code: '',
          type: '',
          status: '',
          tel: ''
        }
      ],
      addUnitForm: [
        {
          rowId: undefined
        }
      ],
      addProjectForm: [
        {
          rowId: undefined,
          provinceId: '',
          provinceName: '',
          cityId: '',
          districtId: '',
          townId: '',
          villageId: '',
          name: '',
          code: '',
          type: '',
          status: '',
          tel: '',
          file: ''
        }
      ],
      fileForm: {},
      provinces: [],
      citys: [],
      districts: [],
      communitys: [],
      buildings: [],
      deviceTable: [],
      exampleFormRules: {
        name: [{ required: true, message: '请输入项目名称', trigger: 'blur' }]
      },
      addUnitRules: {
        name: [{ required: true, message: '请输入单元名称', trigger: 'blur' }],
        startCount: [
          { required: true, validator: checkStartNum, trigger: 'blur' }
        ],
        count: [{ required: true, validator: checkNum, trigger: 'blur' }],
        status: [
          { required: true, message: '请选择单元状态', trigger: 'change' }
        ]
      },
      addProjectFormRules: {
        // communityId: [
        //   { required: true, message: '请选择小区', trigger: 'change' }
        // ],
        name: [{ required: true, message: '请输入项目名称', trigger: 'blur' }],
        status: [
          { required: true, message: '请选择企业状态', trigger: 'change' }
        ]
      },
      queryForm: {
        current: 1,
        pages: 0,
        total: 0,
        size: 10,
        ascs: '',
        descs: '',
        importance: undefined,
        title: undefined,
        cnName: undefined
      },
      records: []
    }
  },
  created() {
    this.doQuery()
  },
  methods: {
    chooseAddNum(val) {
      if (val === '2') {
        this.single = false
        this.double = true
      }
      if (val === '1') {
        this.single = true
        this.double = false
      }
    },
    openCreateDialog() {
      this.addProjectForm = {}
      this.citys = []
      this.districts = []
      this.towns = []
      this.villages = []
      this.communitys = []
      this.addBulidVisible = true
      this.$refs.addProjectForm && this.$refs.addProjectForm.resetFields()
    },
    saveProjectForm() {
      this.$refs.addProjectForm.validate(valid => {
        if (valid) {
          saveProject(this.addProjectForm).then(
            ({ data: { data, msg, code } }) => {
              if (code === 0) {
                this.doQuery()
                this.addBulidVisible = false
              }
              this.$message({
                showClose: true,
                message: msg,
                type: code === 0 ? 'success' : 'error'
              })
            }
          )
        } else {
          return false
        }
      })
    },
    openFileDialog() {
      this.addProjectForm = {}
      this.citys = []
      this.districts = []
      this.towns = []
      this.villages = []
      this.communitys = []
      this.fileForm = {}
      this.fileVisible = true
      this.$refs.fileForm && this.$refs.fileForm.resetFields()
    },
    uploadFile() {
      const excle = new FormData()
      excle.append('file', this.fileForm.param)
      excle.append('communityName', this.addProjectForm.communityName)
      excle.append('cityId', this.addProjectForm.cityId)
      excle.append('communityId', this.addProjectForm.communityId)
      excle.append('provinceId', this.addProjectForm.provinceId)
      excle.append('districtId', this.addProjectForm.districtId)
      uploadBuildingFile(excle).then(({ data: { data, msg } }) => {
        this.fileVisible = false
        this.$refs.avatarInput.clearFiles()
        this.doQuery()
        this.$message({
          showClose: true,
          message: '导入成功',
          type: 'success'
        })
      })
    },
    closeDialog() {
      this.projectDeviceVisible = false
      this.deviceTable = []
    },
    handleChange(file, fileList) {
      if (
        file.name.substring(file.name.lastIndexOf('.'), file.name.length) !==
        '.xls'
      ) {
        this.$message({
          showClose: true,
          message: '只能上传xls文件',
          type: 'error'
        })
        this.$refs.avatarInput.clearFiles()
        return
      }
      this.fileForm.param = file.raw
    },
    addHandleSelect(item) {
      this.addProjectForm.communityId = item.rowId
      this.addProjectForm.communityName = item.name
    },
    handleSortChange({ column, prop, order }) {
      this.queryForm.ascs = ''
      this.queryForm.descs = ''
      if (order) {
        if (order === 'ascending') {
          this.queryForm.ascs = column.sortBy
        } else {
          this.queryForm.descs = column.sortBy
        }
      }
      this.queryForm.current = 0
      this.doQuery()
    },
    handleCurrentChange(current) {
      this.queryForm.current = current
      this.doQuery()
    },
    handleSizeChange(size) {
      this.queryForm.size = size
      this.doQuery()
    },
    doSearchQuery() {
      this.queryForm.current = 1
      this.doQuery()
    },
    doQuery() {
      this.loading = true
      queryProject(this.queryForm).then(({ data: { data } }) => {
        this.queryForm.current = data.current
        this.queryForm.pages = data.pages
        this.queryForm.total = data.total
        this.queryForm.size = data.size
        this.records = data.records
        this.loading = false
      })
      queryProvince().then(({ data: { data } }) => {
        this.provinces = data
        this.loading = false
      })
    },
    handleDelete(rowId) {
      this.$confirm('此操作将永久删除该项目, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteProject(rowId).then(({ data: { data, msg } }) => {
          this.doQuery()
          this.$message({
            showClose: true,
            message: msg,
            type: 'success'
          })
        })
      })
    },
    editProject({ rowId }) {
      this.exampleForm = {}
      this.$refs.exampleForm && this.$refs.exampleForm.resetFields()
      queryProjectDetail(rowId).then(({ data: { code, data, msg } }) => {
        this.dialogFormVisible = true
        if (code === 0) {
          this.exampleForm = {
            rowId: data.rowId,
            name: data.name,
            phone: data.phone,
            addr: data.addr,
            projectUser: data.projectUser
          }
        }
      })
    },
    updateProject() {
      this.$refs.exampleForm.validate(valid => {
        if (valid) {
          this.dialogFormVisible = false
          updateProject(this.exampleForm).then(
            ({ data: { data, msg, code } }) => {
              if (code === 0) {
                this.doQuery()
              }
              this.$message({
                showClose: true,
                message: msg,
                type: code === 0 ? 'success' : 'error'
              })
            }
          )
        } else {
          return false
        }
      })
    },
    openProjectDevice({ rowId }) {
      this.projectDeviceVisible = true
      findDeviceByProject(rowId).then(({ data: { code, data, msg } }) => {
        this.deviceTable = data
      })
    },
    saveUnit() {
      this.$refs.addUnitForm.validate(valid => {
        if (valid) {
          this.addUnitVisible = false
          saveUnit(this.addUnitForm).then(({ data: { data, msg, code } }) => {
            if (code === 0) {
              this.doQuery()
            }
            this.$message({
              showClose: true,
              message: msg,
              type: code === 0 ? 'success' : 'error'
            })
          })
        } else {
          return false
        }
      })
    },
    cascade(rowId, level, param) {
      if (param === 'query') {
        if (rowId !== '') {
          switch (level) {
            case 'chooseProvince':
              getCity(rowId).then(({ data: { data } }) => {
                this.queryForm.cityId = ''
                this.queryForm.cityName = ''
                this.queryForm.districtId = ''
                this.queryForm.communityId = ''
                this.queryForm.rowId = ''
                this.citys = []
                this.districts = []
                this.communitys = []
                this.buildings = []
                this.citys = data
              })
              return
            case 'chooseCity':
              getDistrict(rowId).then(({ data: { data } }) => {
                this.queryForm.districtId = ''
                this.queryForm.communityId = ''
                this.queryForm.rowId = ''
                this.districts = []
                this.communitys = []
                this.buildings = []
                this.districts = data
              })
              return
            case 'chooseRegin':
              selectAllCommunity(rowId).then(({ data: { data } }) => {
                this.queryForm.communityId = ''
                this.queryForm.rowId = ''
                this.communitys = []
                this.buildings = []
                this.communitys = data
              })
              return
            case 'chooseCommunity':
              selectByCommunityIdBuilding(rowId).then(({ data: { data } }) => {
                this.queryForm.rowId = ''
                this.buildings = []
                this.buildings = data
              })
              return
            case 'chooseBuliding':
              selectByCommunityIdBuilding(this.queryForm.communityId).then(
                ({ data: { data } }) => {
                  this.buildings = data
                }
              )
              return
          }
        } else {
          switch (level) {
            case 'chooseProvince':
              this.queryForm.cityId = ''
              this.queryForm.districtId = ''
              this.queryForm.communityId = ''
              this.queryForm.rowId = ''
              this.citys = []
              this.districts = []
              this.towns = []
              this.villages = []
              this.communitys = []
              this.buildings = []
              return
            case 'chooseCity':
              this.queryForm.districtId = ''
              this.queryForm.communityId = ''
              this.queryForm.rowId = ''
              this.districts = []
              this.communitys = []
              this.buildings = []
              return
            case 'chooseRegin':
              this.queryForm.communityId = ''
              this.queryForm.rowId = ''
              this.communitys = []
              this.buildings = []
              return
            case 'chooseCommunity':
              this.queryForm.rowId = ''
              this.buildings = []
              return
            // case 'chooseBuliding':
            //   this.queryForm.rowId = ''
            //   return
          }
        }
      } else if (param === 'addBulid') {
        if (rowId !== '') {
          switch (level) {
            case 'chooseProvince':
              getCity(rowId).then(({ data: { data } }) => {
                this.addProjectForm.cityId = ''
                this.addProjectForm.districtId = ''
                this.addProjectForm.communityId = ''
                this.citys = []
                this.districts = []
                this.communitys = []
                this.citys = data
              })
              return
            case 'chooseCity':
              getDistrict(rowId).then(({ data: { data } }) => {
                this.addProjectForm.districtId = ''
                this.addProjectForm.communityId = ''
                this.districts = []
                this.communitys = []
                this.districts = data
              })
              return
            case 'chooseRegin':
              selectAllCommunity(rowId).then(({ data: { data } }) => {
                this.addProjectForm.communityId = ''
                this.communitys = []
                this.communitys = data
              })
              return
            case 'chooseCommunity':
              selectAllCommunity(this.addProjectForm.districtId).then(
                ({ data: { data } }) => {
                  const datas = this.communitys.find(
                    item => item.rowId === rowId
                  )
                  this.addProjectForm.communityName = datas.name
                  this.communitys = data
                }
              )
              return
          }
        } else {
          switch (level) {
            case 'chooseProvince':
              this.addProjectForm.cityId = ''
              this.addProjectForm.districtId = ''
              this.addProjectForm.communityId = ''
              this.citys = []
              this.districts = []
              this.towns = []
              this.villages = []
              this.communitys = []
              return
            case 'chooseCity':
              this.addProjectForm.districtId = ''
              this.addProjectForm.communityId = ''
              this.addProjectForm.rowId = ''
              this.districts = []
              this.communitys = []
              return
            case 'chooseRegin':
              this.addProjectForm.communityId = ''
              this.addProjectForm.rowId = ''
              this.communitys = []
              return
            // case 'chooseCommunity':
            //   this.addProjectForm.rowId = ''
            //   return
            // case 'chooseBuliding':
            //   this.queryForm.rowId = ''
            //   return
          }
        }
      }
    }
  },
  components: {}
}
</script>

<style scoped>
.upload-demo {
  line-height: 32px;
}
</style>
